<?php

$alphabet = @$_GET['alphabet'];
$listfilter = "";
$listfilter = @$_GET['listfilter'];
$WhereFilter = "";
$listfilter_htmlcode = $PACTS_cfg->remove_duplicated_amps("listfilter=".$listfilter."&amp;");

if ($alphabet==null or $alphabet == ""){
    $alphabet="all";
}
$alphabet_htmlcode = 'alphabet='.$alphabet.'';


$FamilyId = @$_GET['FamilyId'];

$WhereFilter = $PACTS_cfg->getListHeader($listfilter_htmlcode,$alphabet,"index.php?view=Fmly_az_list&amp;","index.php?view=Fmly_allentries&amp;","Families",$listfilter,"FamilyId=$FamilyId");

$link = "index.php?view=Fmly_az_list&amp;".$alphabet_htmlcode."&amp;";

$submitData = @$_POST['submitData'];
$SubmitDeleteFamilyPhoto = @$_POST['SubmitDeleteFamilyPhoto'];
$FamilyName = $PACTS_cfg->getFormattedFamilyShortName($FamilyId," ");

$PHPSESSID = @$_GET['PHPSESSID'];
//echo "<pre>";
//print_r($_POST);
//echo "</pre>";

if($PACTS_cfg->getUserCanModify()) {
    $strChanges = "";
    if($submitData == "Update information" or $SubmitDeleteFamilyPhoto=="Delete Photo")
    {
        $PACTS_cfg->PMA_gpc_extract($HTTP_POST_VARS, $GLOBALS);
    }

    //	echo "<table><tr>";
    echo '<p />'."\n";
    echo '<div id="details-section">'."\n";
    echo '<div id="viewHeading">'."\n";

    echo '<p class="IndvName">'.$FamilyName.' Family:</p>'."\n";
    echo $PACTS_cfg->getFmlyNavBar("", $FamilyId."&amp;".$listfilter_htmlcode.$alphabet_htmlcode, TRUE, FALSE, TRUE, "Fmly_view","",TRUE,TRUE,"",FALSE);
    echo '</div>'."\n";
    echo '<p class="titlename1">Edit Family</p>'."\n";

    if($submitData == "Update information" or $SubmitDeleteFamilyPhoto=="Delete Photo")
    {
        $PACTS_cfg->PMA_gpc_extract($HTTP_POST_VARS, $GLOBALS);
        //	$IndividualId = $fields['IndividualId'];

        $fields_changes = array();
        $fields_changes_prev = array();
        $fields_invalid = array();
        $fields_changes_SQL = array();

        // check fields for validity
        $bInvalidField = FALSE;

        foreach ($fields as $fields_key => $fields_value) {
            //		echo "checking... $fields_key<p>";

            if($fields_prev[$fields_key] == $fields_value) {
                // no change with data
            }
            else
            {
                if(is_array($fields_value)) {
                    // must be a date
                    // put date back together and check validity
                    $mon = getNumMonthFromString($fields_value['Month']);
                    $day = getNumDayOfMonthFromString($fields_value['DayOfMonth']);
                    $year = $fields_value['Year'];
                    if( is_numeric($day) && is_numeric($mon) && is_numeric($year) && checkdate( $mon, $day, $year )) {
                        //	valid
                    }
                    else{
                        // invalid
                        echo "<b>Invalid $fields_key : $day ".$fields_value['Month']." $year</b><p>";
                        $bInvalidField = TRUE;
                        $fields_changes[$fields_key] = TRUE;
                    }

                    $compileDate=$day."-".$mon."-".$year;
                    if($day=="" and ($mon=="" or $mon==0) and $year=="") {
                        $compileDate = "blank";
                    }
                    $fields_changes[$fields_key] = $compileDate;



                    $fields_changes_SQL[$fields_key] = $year."-".$mon."-".$day;
                    // get prev date
                    $mon = getNumMonthFromString($fields_prev[$fields_key]['Month']);
                    $day = $fields_prev[$fields_key]['DayOfMonth'];
                    $year = $fields_prev[$fields_key]['Year'];
                    $compileDate=$day."-".$mon."-".$year;
                    if($day=="" and ($mon=="" or $mon==0) and $year=="") {
                        $compileDate = "blank";
                    }
                    $fields_changes_prev[$fields_key] = $compileDate;

                }else
                {
                    if($fields_key == "FamilyPhoto") {
                    } else{
                        $fields_changes_SQL[$fields_key] = $fields_value;
                        $fields_changes[$fields_key] = $fields_value;
                        $fields_changes_prev[$fields_key] = $fields_prev[$fields_key];
                    }
                }
            }
        }

        // do photo
        if (@$_FILES['FamilyPhoto']['name']) {
            //echo "got photo <p>";
            $contents = mysql_escape_string(fread(fopen($_FILES['FamilyPhoto']['tmp_name'],"r"), filesize($_FILES['FamilyPhoto']['tmp_name'])));
            $fields_changes_SQL['FamilyPhoto'] = $contents;
            $fields_changes['FamilyPhoto'] = $contents;
            array_push ($fields_changes_prev, "FamilyPhoto" );
        }

        // build SQL for operation
        $updateSql = "UPDATE Family SET ModificationTMS = now(), ModificationUserId = '".$_SESSION['username']."'";

        ///////////////////////////////////////////
        if(count($fields_changes)>0) {
            echo "<hr>";
            foreach ($fields_changes as $fields_key => $fields_value) {

                //		echo "checking... $fields_key<p>";

                if($fields_key == "FamilyPhoto") {
                    $hexvalue = $contents;
                    $updateSql .= ", FamilyPhoto = '".$contents."' ";
                    $updateSql .= ", FamilyPhotoName = '".$_FILES['FamilyPhoto']['name']."' ";
                    $updateSql .= ", FamilyPhotoSize = '".$_FILES['FamilyPhoto']['size']."' ";
                    $updateSql .= ", FamilyPhotoType = '".$_FILES['FamilyPhoto']['type']."' ";
                    echo "<p class=\"changes\">'$fields_key' to be updated</p><br />\n";
                    $PACTS_cfg->InsertAuditTrailEntry("n/a", $_FILES['FamilyPhoto']['name']." (".$_FILES['FamilyPhoto']['size']." bytes , ".$_FILES['FamilyPhoto']['type'].")" , "Edit", "Family", "FamilyPhoto" ,$_SESSION['username'], $_SERVER['PHP_SELF'], $FamilyId);

                    //function $PACTS_cfg->InsertAuditTrailEntry($OldData, $NewData, $ChangeType, $TableName, $FieldName, $UserId, $PageName,$RecordId)


                } else{

                    if(!strlen($fields_value)>0) {
                        //					$fields_value = "NULL";
                        $updateSql .= ", $fields_key = NULL ";
                        $PACTS_cfg->InsertAuditTrailEntry($fields_changes_prev[$fields_key], $fields_value ,"Edit","Family",$fields_key,$_SESSION['username'], $_SERVER['PHP_SELF'],$FamilyId);
                    } else {
                        $updateSql .= ", $fields_key = '".$fields_changes_SQL[$fields_key]."' ";
                        $PACTS_cfg->InsertAuditTrailEntry($fields_changes_prev[$fields_key], $fields_value ,"Edit","Family",$fields_key,$_SESSION['username'], $_SERVER['PHP_SELF'],$FamilyId);

                    }

                    echo "<p class=\"changes\">'$fields_key' changed from ";
                    echo "'".$fields_changes_prev[$fields_key]."' --> ";
                    echo "'$fields_value' </p><br />\n";
                }
            }


            $updateSql .= " WHERE FamilyId = $FamilyId;";
            //		echo "<p>$updateSql<p>";
            $result_update = mysql_query($updateSql);
            echo "<hr>";
        }
        else
        {
            if($SubmitDeleteFamilyPhoto!="Delete Photo")  {
                echo "<hr>";
                echo "<p class=\"changes\">no changes!</p>";
                echo "<hr>";
            }
        }
    }

    //
    if($SubmitDeleteFamilyPhoto=="Delete Photo") {
        // delete stored photo
        $updateSql = "UPDATE Family SET ModificationTMS = now(), ModificationUserId = '".$_SESSION['username']."'";
        $updateSql .= ", FamilyPhoto = '' ";
        $updateSql .= ", FamilyPhotoName = '' ";
        $updateSql .= ", FamilyPhotoSize = '' ";
        $updateSql .= ", FamilyPhotoType = '' ";
        $updateSql .= " WHERE FamilyId = $FamilyId;";
        $result_update = mysql_query($updateSql);
        $PACTS_cfg->InsertAuditTrailEntry("FamilyPhoto", "" ,"Edit","Family","FamilyPhoto",$_SESSION['username'], $_SERVER['PHP_SELF'],$FamilyId);
        echo "<hr>"."\n";
        echo "<p class=\"changes\">Photo deleted</p ><br />\n";
        echo "<hr>"."\n";
    }

    if($FamilyId > 0)
    {
        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

        $oTableCol = new TableColumn("Family",$PACTS_cfg->aMySQLType);

        $mycount=0;
        $sql =  "SELECT * FROM Family WHERE FamilyId=".$FamilyId.";";
        $result = mysql_query($sql,$PACTS_cfg->dblink);
        $resultsnumber_Indv = mysql_numrows($result);
        $myrow = mysql_fetch_array($result);

        // gather column information
        $sql_cols = "SHOW COLUMNS FROM Family;";
        $result_cols = mysql_query($sql_cols,$PACTS_cfg->dblink);
        $Indv_ColumnInfo = mysql_fetch_array($result_cols);

        $URLmessage="Family details updated!";

        echo "\n";

        echo '<form method="post" enctype="multipart/form-data" action="'.$HTTP_SERVER_VARS['PHP_SELF'].'?view=Fmly_edit&amp;FamilyId='.$FamilyId.'&amp;URLmessage='.$URLmessage.'&amp;PHPSESSID='.$PHPSESSID.'">'."\n";
        echo '<div id="viewDetailsC2">'."\n";
        echo '<input type="hidden" name="fields[FamilyId]" value="'.$FamilyId.'" />'."\n";
        echo '<input type="hidden" name="fields_prev[FamilyId]" value="'.$FamilyId.'" />'."\n";
        //        echo "\n\n<table border=0 cellpadding=0 cellspacing=0>"."\n";
        while ($Indv_ColumnInfo = mysql_fetch_array($result_cols)) {
            $mycount++;
            $Field = $Indv_ColumnInfo["Field"];
            $Value = $myrow[$Field];
            $DayOfMonth = "";
            $Month = "";
            $Year = "";
            $Ychecked = "";
            $Nchecked = "";
            $inputOptions = "";
            // conditions for different fields on screen
            // e.g. Readonly for ModificationTMS and ModificationUserId
            $bREADONLY = FALSE;
            $bHIDDEN = FALSE;

            if (strtoupper($Field) == "FAMILYPHOTONAME" || strtoupper($Field) == "FAMILYPHOTOTYPE"|| strtoupper($Field) == "FAMILYPHOTOSIZE"){
                continue;
            }


            // if field ends with UserId or TMS then READONLY
            // if field ends with IndividualId then HIDDEN

            if(strtoupper( substr($Field, strlen($Field)-6,6)) == "USERID") {
                $bREADONLY = FALSE;
                $inputOptions = $PACTS_cfg->inputREADONLY  ;
            }


            if(strtoupper( substr($Field, strlen($Field)-3,3)) == "TMS") {
                $bREADONLY = FALSE;
                $inputOptions = $PACTS_cfg->inputREADONLY  ;
            }

            $strCheckFor = "PHOTOTYPE";
            if(strtoupper( substr($Field, strlen($Field)-strlen($strCheckFor),strlen($strCheckFor))) == $strCheckFor) {
                $bHIDDEN = TRUE;
            }

            $strCheckFor = "PHOTOSIZE";
            if(strtoupper( substr($Field, strlen($Field)-strlen($strCheckFor),strlen($strCheckFor))) == $strCheckFor) {
                $bHIDDEN = TRUE;
            }
            $strCheckFor = "PHOTONAME";
            if(strtoupper( substr($Field, strlen($Field)-strlen($strCheckFor),strlen($strCheckFor))) == $strCheckFor) {
                $bHIDDEN = TRUE;
            }


            echo "\n<ul>\n";

            list ($CType, $CSize) = $oTableCol->getTypeSize($Field);
            echo "  ";

            $fieldDescription = trim($PACTS_cfg->getFieldDescription("Family", $Field));
            if(!strlen($fieldDescription)>0 and !$bHIDDEN)  {
                $fieldDescription = "No description available";
            }

            if(!$bHIDDEN) {
                echo '<li class="viewDetailsHeader" title="'.$fieldDescription.'" >'.$Field;
                //                echo '<td  title="'.$fieldDescription.'" '.$PACTS_cfg->titleTxtClass.'>'.$Field.'</td>';
                echo '</li>'."\n";
                echo '<li class="viewDetailsData">'."\n";
            }

            if(@$PACTS_cfg->aFieldLookUpTableList[$Field] and !$bHIDDEN) {
                //echo "<h2>$mycount</h2>";
                echo '<!-- start aFieldLookUpTableList -->'."\n";

                echo "".$PACTS_cfg->getLookupTableHTML($Field,"fields[".$Field."]",$Value,$mycount );
                echo '</li>'."\n";
                echo '<li class="viewDetailsLookup">'."\n";

                //                echo "<table border=0 cellspacing=0 cellpadding=0>\n<tr>"."\n";
                //                echo "<td class=\"txtbot\">"."\n";

                //                echo "</td>"."\n";
                if (strstr($Field, "StreetTypeCode")) {
                    //					' find string up to Suburb
                    $iposA = strpos($Field, "Suburb");
                    $strPreFix = substr($Field, 0, $iposA);
                    //                    echo "<td rowspan=2 class=\"txtbot\">&nbsp;";
                    echo $PACTS_cfg->getSelectListOfCommonlyUsedStreetTypeCodes($Field,"Residential",$mycount,"</td><td rowspan=2 class=\"txtcentre\">&nbsp;" );
                    //                    echo "</td>"."\n";
                }
                if (strstr($Field, "PremiseType")) {
                    //					' find string up to Suburb
                    $iposA = strpos($Field, "PremiseType");
                    $strPreFix = substr($Field, 0, $iposA);
                    //                    echo "<td rowspan=2 class=\"txtbot\">&nbsp;";
                    echo $PACTS_cfg->getSelectListOfCommonlyUsedPremiseTypes($Field,"",$mycount,"</td><td rowspan=2 class=\"txtcentre\">&nbsp;" );
                    //                    echo "</td>"."\n";
                }
                /*
                echo '<p class="smalltxt">'."\n";
                echo "(".$PACTS_cfg->aFieldLookUpTableList[$Field]['Description']."";
                if(@strlen($PACTS_cfg->aFieldLookUpTableList[$Field]['Description2'])>0) {
                    echo ", ".@$PACTS_cfg->aFieldLookUpTableList[$Field]['Description2']."";
                }
                echo ")</p><br />";
*/
                //                echo "".$PACTS_cfg->getLookupTableHTML($Field,"fields[".$Field."]",$Value,$mycount);
                echo "\n";
                echo '<input type="hidden" name="fields_prev['.$Field.']" value="'.$Value.'" />';
                //                echo "</td></tr></table>\n";
                //                echo "</td>\n";

                echo '<!-- end aFieldLookUpTableList -->'."\n";
                echo '</li>'."\n";


            }else
            {
                switch (TRUE) {
                    case ($PACTS_cfg->aMySQLType[trim($CType)]==$PACTS_cfg->textbox AND $CSize<$PACTS_cfg->intMaxInputBoxSize and !$bHIDDEN):
                        //
                        // TEXTBOX
                        //
                        echo "\n";
                        echo '<input type="hidden" name="fields_prev['.$Field.']" value="'.$Value.'" />';

                        echo '<input type="text" id="'.$Field.'" name="fields['.$Field.']" value="'.$Value.'" size="30" maxlength="'.$CSize.'" class="'.$PACTS_cfg->textbox.'" '.$inputOptions.' />';

                        break;


                    case ($PACTS_cfg->aMySQLType[trim($CType)]==$PACTS_cfg->textareabox OR ($PACTS_cfg->textbox AND $CSize>=$PACTS_cfg->intMaxInputBoxSize ) and !$bHIDDEN) :
                        //
                        // TEXTAREABOX
                        //
                        if(is_null($CSize) or $CSize=="" or (int)$CSize ==0) {
                            $CSize = $PACTS_cfg->intTextAreaDefaultCharCount;
                        }
                        // if size is over 50 then use textarea
                        // <textarea name="address" rows="5" cols="35"></textarea>
                        echo "\n\n";
                        echo '<input type="hidden" name="fields_prev['.$Field.']" value="'.$Value.'" />';
                        echo "\n\n";
                        echo '<textarea id="'.$Field.'" name="fields['.$Field.']" rows="'.((int)($CSize/$PACTS_cfg->intTextAreaColSize)+1).'" cols="'.$PACTS_cfg->intTextAreaColSize .'" '.$inputOptions.' class="tb">'.$Value.'</textarea>';




                        break;

                    case ($PACTS_cfg->aMySQLType[trim($CType)]==$PACTS_cfg->enumcheckbox and !$bHIDDEN):
                        echo "\n\n";
                        if($Value=='Y') {
                            $Ychecked = ' checked="checked" ';
                        }else
                        {
                            $Nchecked = ' checked="checked" ';
                        }
                        echo '<input type="hidden" name="fields_prev['.$Field.']" value="'.$Value.'" />';
                        echo "\n";
                        echo '<input type="radio" name="fields['.$Field.']" value="Y"'.$Ychecked .' /><label>Y</label>';
                        echo "\n";
                        echo '<input type="radio" name="fields['.$Field.']" value="N"'.$Nchecked .' /><label>N</label>';

                        break;
                    case ($PACTS_cfg->aMySQLType[trim($CType)]==$PACTS_cfg->imagebox and !$bHIDDEN):
                        echo '<table border="0">';
                        echo '<tr>';
                        echo '<td align="center">';
                        if(strlen($Value)==0) {
                            echo '&nbsp;';
                        }else{
                            echo '<img src="index.php?view=display_image_thumb&amp;FamilyId='.$FamilyId.'&height=70"  BORDER="0" ALT="">';
                        }
                        echo '</td><td align="center">';
                        echo "Click browse to update image<br />";

                        if(strlen($Value)>0) {
                            echo "<p class=\"smalltxt\"><input type=\"checkbox\" id=\"deleteFamilyPhoto\" name=\"SubmitDeleteFamilyPhoto\" value=\"Delete Photo\" class=\"smalltxt\" title=\"Delete Photo\" />&nbsp;Delete Photo</p>\n";
                        }

                        echo "</td></tr>";
                        echo "<tr><td>";
                        echo "";

                        if(strlen($Value)==0) {
                            echo "<p class=\"smalltxt\">No image!</p>";
                        }else{
                            echo "<p class=\"smalltxt\">".(int)(strlen($Value)/1024)."Kb Image File</p>";
                        }
                        echo "</td><td>";
                        echo '<input type="hidden" name="MAX_FILE_SIZE" value="1000000000" />';
                        echo '<input type="file" name="FamilyPhoto" accept="image/gif,image/jpeg,image/png" /><br />';
                        echo '<input type="hidden" name="fields_prev[';
                        echo "FamilyPhoto";
                        echo ']" value="" /><br />';
                        echo "</td>"."\n";
                        echo "</tr>";
                        echo "</table>";

                        break;
                    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////
                    case ($PACTS_cfg->aMySQLType[trim($CType)]==$PACTS_cfg->timebox and !$bHIDDEN):
                        $tmp1 = $PACTS_cfg->myts_date("H:i:s - l jS F y",$Value);
                        print "$tmp1";

                        break;
                    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////
                    case ($PACTS_cfg->aMySQLType[trim($CType)]== $PACTS_cfg->datebox and !$bHIDDEN):
                        // 'YYYY-MM-DD' format
                        $mydate = myts_date("d-F-Y",$Value,0,5,8);
                        $DayOfMonth = myts_date("d",$Value,0,5,8);
                        $Month = myts_date("F",$Value,0,5,8);
                        $Year = myts_date("Y",$Value,0,5,8);

                        echo '<table border="0" cellpadding="0">'."\n";
                        echo '<tr>'."\n";
                        echo '<td align="center"><p class="smalltxt">Day</p></td>'."\n";
                        echo '<td align="center"><p class="smalltxt">Month</p></td>'."\n";
                        echo '<td align="center"><p class="smalltxt">Year</p></td>'."\n";
                        echo "</tr>\n";
                        echo "<tr>\n";
                        echo "<td>".$PACTS_cfg->getDayOfMonthHTML('fields['.$Field.'][DayOfMonth]',$DayOfMonth)."</td>\n"."\n";
                        echo "<td>".$PACTS_cfg->getMonthHTML('fields['.$Field.'][Month]',$Month)."</td>\n"."\n";
                        echo '<td><input type="text" name="fields['.$Field.'][Year]" value="'.$Year.'" size="4" maxlength="4" class="'.$datebox.'" />'."\n";

                        echo '<input type="hidden" name="fields_prev['.$Field.'][DayOfMonth]" value="'.$DayOfMonth.'"/>'."\n";
                        echo '<input type="hidden" name="fields_prev['.$Field.'][Month]" value="'.$Month.'"/>'."\n";
                        echo '<input type="hidden" name="fields_prev['.$Field.'][Year]" value="'.$Year.'"/>'."\n";

                        echo '</td>'."\n";
                        echo "\n</tr>\n</table>"."\n";

                        break;
                } // end switch

                if (strstr($Field, "Suburb")) {
                    //					' find string up to Suburb
                    $iposA = strpos($Field, "Suburb");
                    $strPreFix = substr($Field, 0, $iposA);
                    echo '</li>'."\n".'<li class="viewDetailsLookup">'."\n";

                    echo $PACTS_cfg->getSelectListOfCommonlyUsedSuburbs($Field,$strPreFix,$mycount,"" )."\n";
                }

//                print_r($Indv_ColumnInfo);

                echo "\n</li>\n";
            }// end else
            echo "\n</ul>\n\n";
        }
//        echo '<tr><td colspan="2" align="center">'."\n";
    echo '<ul><li class="viewDetailsHeader"></li>'."\n";
    echo '<li class="viewDetailsDataEdit">'."\n";
        echo '<input type="submit" name="submitData" class="smalltxtInput" value="Update information" />'."\n";
    echo '</li></ul>'."\n";
    echo '<!-- end DIV viewDetailsC1 -->'."\n";
        echo '</div>'."\n";
        echo '</form>'."\n"."\n";
    echo '</div>'."\n";
    }
}
else {
    echo '<div id="details-section">'."\n";
    echo '<div id="viewDetailsC2">'."\n";

    echo '<p class="errmsg1">Error! You do not have permission to modify data!</p>'."\n";
    echo '</div>'."\n";
    echo '</div>'."\n";

} 

?>